import React from 'react';
import classnames from 'classnames';
import PropTypes from 'prop-types';

import { isWechat } from '@facejs/macro';
import { Image, View } from '@facejs/ui';

import s from './index.mini.m.less';

const getRandomKey = () => {
    return Math.random().toString(36).substring(2);
};
export default class LazyImage extends React.PureComponent {
    static propTypes = {
        src: PropTypes.string, // 图片链接
        className: PropTypes.string, // 图片class
        loaded: PropTypes.bool, // 图片是否已经被加载
    };

    static defaultProps = {
        src: '', // 图片链接
        className: '', // 图片class
        loaded: false, // 图片是否已经被加载
    };

    constructor(props) {
        super(props);

        this.state = {
            showImg: this.props.loaded,
            classKey: getRandomKey(),
        };
    }

    componentDidMount() {
        if (isWechat) this.initWechatImg();
    }

    initWechatImg = () => {
        const { classKey, showImg } = this.state;
        if (showImg) return;
        //真正的图片懒加载
        let IntersectionObserver = wx.createIntersectionObserver();
        IntersectionObserver.relativeToViewport().observe(`.img-${classKey}`, (res) => {
            if (res.intersectionRatio > 0) {
                this.setState(
                    {
                        showImg: true,
                    },
                    () => {
                        IntersectionObserver.disconnect();
                    }
                );
            }
        });
    };

    render() {
        const { src, className, ...restProps } = this.props;
        const { classKey, showImg } = this.state;
        return (
            <View className={classnames(className, s.imgbox)}>
                <Image
                    className={classnames(`img-${classKey}`, s.img)}
                    mode="widthFix"
                    src={showImg ? src : ''}
                    {...restProps}
                />
            </View>
        );
    }
}
